<template>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" :disabled="false">
        <el-form-item label="选择公众号" prop="official_account_id">
            <OfficialAccounts
                :public-data="{ id: formData.official_account_id }"
                :disabled="isDetail"
                @submit="v => v && (formData.official_account_id = v)" />
        </el-form-item>
        <el-form-item label="所属分组" prop="group_id">
            <el-cascader
                ref="cascaderRef"
                v-model="formData.group_id"
                :props="{
                    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
                    emitPath: false,
                    multiple: false,
                    label: 'name',
                    value: 'id'
                }"
                :options="groupOptions"
                :disabled="isDetail"
                @change="orgChange" />
        </el-form-item>
        <el-form-item label="活动标题" prop="activity_name">
            <el-input
                v-model.trim="formData.activity_name"
                maxlength="15"
                show-word-limit
                placeholder="请输入标题名称"
                :disabled="isDetail" />
        </el-form-item>
        <el-form-item label="活动有效期" prop="period_type">
            <el-radio-group v-model="formData.period_type" prop="period_type" :disabled="isDetail || isEdit">
                <el-radio :label="1">永久</el-radio>
                <el-radio :label="2">自定义期限</el-radio>
            </el-radio-group>
            <teamplate v-if="formData.period_type === 2">
                <el-date-picker
                    v-model="formData.activity_time"
                    type="datetimerange"
                    :disabled-date="disabledDate"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :disabled="isDetail || isEdit" />
            </teamplate>
        </el-form-item>
        <el-form-item label="活动描述">
            <el-input
                v-model.trim="formData.description"
                :rows="5"
                maxlength="100"
                type="textarea"
                show-word-limit
                placeholder="请输入活动说明"
                :disabled="isDetail" />
        </el-form-item>
        <el-form-item class="table_group">
            <template #label>
                <span class="red">* </span>
                <span>选择群聊</span>
            </template>
            <el-table :data="formData.region" row-key="key" stripe>
                <el-table-column prop="name" label="区域名称" width="240">
                    <template #default="scope">
                        <el-form-item
                            :prop="`region.${scope.$index}.name`"
                            :rules="{ required: true, validator: areaNameValidator, trigger: 'blur' }">
                            <el-input
                                v-model.trim="scope.row.name"
                                class="area-name"
                                :readonly="scope.row.is_default === 1"
                                placeholder="请输入"
                                :disabled="isDetail" />
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="pca_code" label="行政范围" width="420">
                    <template #default="scope">
                        <div v-if="scope.row.is_default !== 1" :key="scope.row.id">
                            <el-cascader
                                v-model="scope.row.pca_code"
                                placeholder="请选择行政区域"
                                class="area-code"
                                :options="city"
                                :props="defaultProps"
                                :disabled="isDetail"
                                collapse-tags
                                collapse-tags-tooltip
                                filterable
                                @visible-change="visible => onVisibleChange(visible, scope.row)"
                                @change="value => onChange(value, scope.row)" />
                        </div>
                        <span v-else> 其他 </span>
                    </template>
                </el-table-column>
                <el-table-column prop="groupchat" label="引流企微外部群" width="265">
                    <template #default="scope">
                        <el-form-item
                            :prop="`region.${scope.$index}.groupchat`"
                            :rules="{ required: true, validator: groupchatValidator }">
                            <div v-if="scope.row.groupchat?.id" class="group-info">
                                <img
                                    v-if="!isDetail"
                                    class="close-icon"
                                    draggable="false"
                                    src="@/assets/image/customer/close_icon.png"
                                    @click="removeGroup(scope)" />
                                <img :src="scope.row.groupchat.avatar" alt="" />
                                <div class="group-name">
                                    <div :title="scope.row.groupchat.name">{{ scope.row.groupchat.name }}</div>
                                    <div :title="scope.row.groupchat.manager_name">
                                        群主：{{ scope.row.groupchat.manager_name }}
                                    </div>
                                </div>
                            </div>
                            <el-button v-else :disabled="isDetail" @click="handleGroupClick(scope.$index)">
                                选择企微外部群
                            </el-button>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="groupchat_num" label="当前群聊人数">
                    <template #default="scope">
                        {{ scope.row.groupchat?.member_nums || '--' }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button
                            v-if="scope.row.is_default !== 1"
                            size="small"
                            :disabled="isDetail"
                            @click="removeItem(scope.$index)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button class="add-item" :disabled="isDetail" @click="onAddItem">添加区域</el-button>
        </el-form-item>
        <el-form-item
            label="入群打标"
            prop="tag_list"
            :rules="[
                {
                    required: formData.tag_flag == 1 ? true : false,
                    message: '请选择入群打标',
                    trigger: 'blur'
                }
            ]">
            <div class="switch_box">
                <el-switch v-model="formData.tag_flag" :active-value="1" :inactive-value="2" />
                <p class="text">打开后，针对老客户的入群的场景标记客户标签</p>
            </div>
            <div v-show="formData.tag_flag == 1" class="zw-el-tags">
                <el-tag v-for="tag in AllTags" :key="tag" :closable="pageType !== 'look'" @close="onClose1(tag)">
                    {{ tag.name }}
                </el-tag>
            </div>
            <div class="select_button_box">
                <el-button v-show="formData.tag_flag == 1" @click="selecTag">选择标签</el-button>
            </div>
        </el-form-item>
    </el-form>
    <GroupChart ref="GroupChartRef" @submit="getGroup" />
    <BatchLabel ref="BatchLabelRef" @save="getTags" />
</template>
<script lang="ts" setup>
import { getGroupList } from '@/api/concreation';
import { reactive, ref, defineExpose, withDefaults, defineProps, onBeforeMount, computed } from 'vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useRoute } from 'vue-router';
import OfficialAccounts from '@/components/OfficialAccounts.vue';
import GroupChart from '@/components/chart/GroupChart.vue';
import BatchLabel from '@/components/BatchLabel.vue';

import { FormData } from '../interface';
import { useStore } from '@/store';
import cityList from '@/assets/js/city';
import { getSetionId } from '@/utils/utils';

/* 默认分组 */
const store = useStore();
const route: any = useRoute();
store.dispatch('setGroupId', +route.query?.group_id);
const isDetail = route.query.type === 'detail';
const isEdit = route.query.type === 'edit';

/* ================================表单内容================================ */
const formRef = ref<FormInstance>();
const BatchLabelRef = ref();
const tag_list_id: any = ref([]);
const cascaderRef: any = ref(null); // 选择分组ref

const AllTags = ref([]);
const formData = reactive<FormData>({
    official_account_id: '',
    activity_name: '', // 活动标题
    group_id: +route.query?.group_id || 0, //分组id
    period_type: 1, // 活动有效期 1-固定 2-永久
    activity_time: ['', ''], //  有效期
    description: '',
    tag_flag: 1,
    tag_list: [],
    region: [
        {
            name: '其他区域',
            is_default: 1,
            groupchat: {},
            pca_code: []
        }
    ]
});
const disabledDate = (data: any) => {
    return +data < +new Date() - 86400000;
};
const periodValidator = (ruls: any, value: any, callback: any) => {
    if (!value) return callback(new Error('请选择活动有效期'));

    if (value === 2) {
        const result = formData.activity_time.every((item: any) => item);
        if (!result) return callback(new Error('请选择活动有效期'));
    }
    callback();
};
const areaNameValidator = (ruls: any, value: any, callback: any) => {
    if (!value) return callback(new Error('请输入区域名称'));

    let repetitionCount = 0;
    for (const iterator of formData.region) {
        if (iterator.name === value) {
            repetitionCount++;
            if (repetitionCount >= 2) {
                return callback(new Error('区域名称不能重复'));
            }
        }
    }
    callback();
};
const groupchatValidator = (ruls: any, value: any, callback: any) => {
    if (!value.id) return callback(new Error('请选择企微外部群'));

    let repetitionCount = 0;
    for (const iterator of formData.region) {
        if (iterator.groupchat.id === value.id) {
            repetitionCount++;
            if (repetitionCount >= 2) {
                return callback(new Error('企微外部群不能重复'));
            }
        }
    }
    callback();
};
const rules = reactive<FormRules>({
    activity_name: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
    official_account_id: [{ required: true, message: '请选择公众号', trigger: 'blur' }],
    period_type: [{ required: true, validator: periodValidator, trigger: 'blur' }],
    group_id: [{ required: true, message: '请选择活动分组', trigger: 'change' }]
});
/* ================================表单内容================================ */

/* ================================选择群聊 ================================*/
const onAddItem = () => {
    formData.region.unshift({
        key: +new Date(),
        is_default: 2,
        name: '',
        pca_code: [],
        groupchat: {},
        members_num: ''
    });
};
const removeItem = (index: number) => {
    formData.region.splice(index, 1);
};
const currentIndex = ref<number>(0);
const GroupChartRef = ref();
const handleGroupClick = (index: number) => {
    currentIndex.value = index;
    GroupChartRef.value.appDialog.visible = true;
    GroupChartRef.value.single = true;
};
const groupchatValidatorAll = () =>
    formRef.value.validateField(Array.from(new Array(formData.region.length)).map((v, i) => `region.${i}.groupchat`));
const getGroup = (val: any) => {
    const data = {
        groupchat: {
            id: val.group_id,
            avatar: val.avatar,
            manager_name: val.manager.name,
            member_nums: val.members_num,
            name: val.name
        }
    };
    Object.assign(formData.region[currentIndex.value], data);
    formRef.value.validateField([`region.${currentIndex.value}.groupchat`]);
};
const removeGroup = ({ row }: any) => {
    row.groupchat_id = '';
    row.groupchat = {};
    row.members_num = '';
    formRef.value.validateField([`region.${currentIndex.value}.groupchat`]);
};
/* ================================选择群聊 ================================*/

/* ================================选择区域================================ */
const CityMap = new Map();
const handleCityMap = (city: Array<any>, gcode?: string | number) => {
    for (const cityItem of city) {
        if (gcode) cityItem.gcode = gcode;
        CityMap.set(cityItem.code, cityItem);
        // childrenCode?.push(cityItem.code)
        const gcode1 = gcode || cityItem.code;
        if (cityItem.children) {
            // cityItem.childrenCode = []
            // handleCityMap(cityItem.children, cityItem.childrenCode)
            handleCityMap(cityItem.children, gcode1);
        }
    }
};
const city = reactive(cityList);
handleCityMap(city);

const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: true,
    label: 'name',
    value: 'code'
};
const pca_code_list = computed(() => {
    const initialCode: Array<any> = [];
    for (const iterator of formData.region) {
        iterator.is_default === 2 && initialCode.push(...iterator.pca_code);
    }
    return initialCode;
});
const setDisabled = (cityData: Array<any>, row_pca_code?: Array<string>, visible?: boolean, disabled?: boolean) => {
    if (visible) {
        // for (const iterator of pca_code_list.value) {
        //   const cityItem = CityMap.get(iterator)

        //   const ispcode = !row_pca_code?.includes(iterator)
        //   cityItem.disabled = ispcode
        //   // lv2
        //   if (cityItem.childrenCode) {
        //     for (const chIterator of cityItem.childrenCode) {
        //       const chItem = CityMap.get(chIterator)
        //       chItem.disabled = !ispcode
        //       //lv3
        //       if (chItem.childrenCode) {
        //         for (const grIterator of chItem.childrenCode) {
        //           CityMap.get(grIterator).disabled = !ispcode
        //         }
        //       }
        //     }
        //   }
        // }

        for (const [index, iterator] of CityMap) {
            const ispcode =
                (pca_code_list.value.includes(`${iterator.pcode}`) && row_pca_code?.includes(`${iterator.pcode}`)) ||
                (pca_code_list.value.includes(`${iterator.gcode}`) && row_pca_code?.includes(`${iterator.gcode}`));
            iterator.disabled =
                ispcode || (pca_code_list.value.includes(iterator.code) && !row_pca_code?.includes(iterator.code));
        }

        // for (const iterator of cityData) {
        //   const ispcode = pca_code_list.value.includes(`${iterator.pcode}`) && row_pca_code?.includes(`${iterator.pcode}`)
        //   if (disabled || ispcode
        //     || pca_code_list.value.includes(iterator.code)
        //     && !row_pca_code?.includes(iterator.code)) {
        //     iterator.disabled = true
        //   }
        //   if (iterator.children) {
        //     setDisabled(iterator.children, row_pca_code, visible, ispcode)
        //   }
        // }
    } else {
        for (const [index, iterator] of CityMap) {
            iterator.disabled = false;
        }
    }
};
const pcaTableRef = ref();
const onChange = (val: any, row: any) => {
    setDisabled(city, row.pca_code, true);
};
const onVisibleChange = (val: boolean, row: any) => {
    setDisabled(city, row.pca_code, val);
};
const onClose1 = (tag: any) => {
    AllTags.value = AllTags.value.filter((item: any) => item.id != tag.id);
    formData.tag_list = getSetionId('id', AllTags.value);
};
/* ================================选择区域================================ */
/* ================================分组================================ */
const groupOptions = reactive<Array<any>>([]);
// 获取活动分组
const onGroupgList = async () => {
    const res: any = await getGroupList({ type: 29, name: '' });
    groupOptions.push(...res.data);
};

// 选择完之后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};

onBeforeMount(() => {
    onGroupgList();
});
/* ================================分组================================ */
// 下一步/获取表单的值
const getParams = async (isValid: boolean) => {
    const result = await formRef.value.validate();
    if (isValid) return result;
    if (result) {
        return {
            ...formData,
            tag_list: formData.tag_list,
            region: formData.region.map((val: any) => ({
                ...val,
                lbs_region_id: val.id,
                groupchat_id: val.groupchat.id,
                groupchat: undefined
            }))
        };
    }
};
const setDetailInfo = (detailInfo: any) => {
    AllTags.value = detailInfo.tag_list;
    tag_list_id.value = getSetionId('id', detailInfo.tag_list);
    detailInfo.activity_time = detailInfo.period_type === 1 ? ['', ''] : detailInfo.activity_time;
    Object.assign(formData, detailInfo);
};
const selecTag = () => {
    BatchLabelRef.value.hasConditiion = false;
    BatchLabelRef.value.dialogData.labelChooseType = 2;
    BatchLabelRef.value.chooseDataArr = [...AllTags.value];
    BatchLabelRef.value.dialogVisible = true;
};
const getTags = (data: any) => {
    AllTags.value = data.data;
    formData.tag_list = getSetionId('id', data.data);
};
defineExpose({
    getParams,
    setDetailInfo
});
</script>

<style lang="scss" scoped>
@import './scss/Form';
</style>
